<template>
  <div class="chat-container">
    <div class="title-container">
      {{ selectedModel }}
    </div>
    <div class="message-container" ref="messageContainer">
      <div class="message-box">
        <div
          v-for="(message, index) in chatHistory"
          :key="index"
          class="message"
          :class="{ 'user': message.sender === 'user', 'ai': message.sender === 'ai' }"
        >
          <!-- 显示头像和名字 -->
          <div class="avatar-container" v-if="message.sender === 'user'">
            <span class="name-label">{{ message.sender === 'user'? 'You' : 'You' }}</span>
            <div class="avatar right">
              <img class="avatar-image" src="./my.jpg" alt="User">
            </div>
          </div>
          <div class="avatar-container" v-if="message.sender === 'ai'">
            <div class="avatar left">
              <img class="avatar-image" src="./ai.png" alt="AI">
            </div>
            <span class="name-label">{{ message.model? message.model : selectedModel }}</span>
          </div>
          <!-- 消息内容 -->
          <div class="message-content">
            <div v-if="message.sender === 'user'" class="user-message">
              <div v-for="(text, textIndex) in message.content" :key="textIndex">
                {{ text }}
              </div>
            </div>
            <div v-if="message.sender === 'ai' && message.isLoading" class="ai-message">
              <div class="loading-animation">
                <span class="loading-dot">.</span>
                <span class="loading-dot">.</span>
                <span class="loading-dot">.</span>
              </div>
              <div>正在生成摘要，请稍候...</div>
            </div>
            <div v-if="message.sender === 'ai' &&!message.isLoading &&!message.isError" class="ai-message">
              <div v-for="(summary, summaryIndex) in message.content" :key="summaryIndex">
                根据我的分析，第 {{ summaryIndex + 1 }} 条短文的摘要为：<o style="color: red;">{{ summary }}</o><br>
              </div>
            </div>
            <div v-if="message.sender === 'ai' && message.isError" class="ai-message">
              <o style="color: red;">系统异常，请稍后再试！</o>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="input-box">
      <select v-model="selectedModel">
        <option value="BART_WEIBO">BART_WEIBO</option>
        <option value="BART_NLPCC">BART_NLPCC</option> <!-- 示例：添加一个其他模型选项 -->
        <!-- 可以添加更多模型选项 -->
      </select>
      <textarea v-model="currentMessage" @keyup.enter="sendMessage" placeholder="请用换行分隔多条短文，在这里提问... " />
      <button @click="sendMessage">发送</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import axios from 'axios';
import { ElMessageBox } from 'element-plus'; // 引入Element Plus的MessageBox用于弹窗

const currentMessage = ref('');
const chatHistory = ref([]);
const selectedModel = ref('BART_WEIBO');
const messageContainer = ref(null);

const sendMessage = async () => {
  if (!currentMessage.value.trim()) return;
  const textsArray = currentMessage.value.trim().split('\n').map(text => text.trim());
  for (const text of textsArray) {
    if (text.length < 50) {
      ElMessageBox.alert('输入的短文长度不足50字符，请重新输入。', '警告', {
        confirmButtonText: '确定'
      });
      return;
    }
    const chineseCount = (text.match(/[\u4e00-\u9fa5]/g) || []).length;
    const englishCount = (text.match(/[a-zA-Z]/g) || []).length;
    if (chineseCount <= englishCount) {
      ElMessageBox.alert('输入的中文文本应多于英文字符，请重新输入。', '警告', {
        confirmButtonText: '确定'
      });
      return;
    }
  }

  chatHistory.value.push({ content: textsArray, sender: 'user' });
  const userMessage = textsArray;
  currentMessage.value = '';

  // 发送用户消息后立即滚动到最新消息位置
  nextTick(() => {
    if (messageContainer.value) {
      messageContainer.value.scrollTop = messageContainer.value.scrollHeight;
    }
  });

  // 添加加载状态消息
  chatHistory.value.push({
    content: [],
    sender: 'ai',
    model: selectedModel.value,
    isLoading: true
  });

  try {
    const response = await axios.post('http://127.0.0.1:5000/summarize', {
      texts: userMessage,
      model_type: selectedModel.value
    });
    const aiResponse = response.data.summaries;

    // 替换加载状态消息为实际回复内容
    chatHistory.value[chatHistory.value.length - 1] = {
      content: aiResponse,
      sender: 'ai',
      model: selectedModel.value,
      isLoading: false,
      isError: false
    };

    setTimeout(() => {
      // AI 回复后滚动到最底部
      nextTick(() => {
        if (messageContainer.value) {
          messageContainer.value.scrollTop = messageContainer.value.scrollHeight;
        }
      });
    }, 0);
  } catch (error) {
    console.error('Error sending message:', error);
    // 处理错误，移除加载状态消息
    chatHistory.value.pop();
    chatHistory.value.push({
      content: [],
      sender: 'ai',
      model: selectedModel.value,
      isLoading: false,
      isError: true
    });

    setTimeout(() => {
      // 滚动到显示错误消息的位置
      nextTick(() => {
        if (messageContainer.value) {
          messageContainer.value.scrollTop = messageContainer.value.scrollHeight;
        }
      });
    }, 0);
  }
};

onMounted(() => {
  // 页面加载时自动滚动到最底部
  nextTick(() => {
    if (messageContainer.value) {
      messageContainer.value.scrollTop = messageContainer.value.scrollHeight;
    }
  });
});
</script>

<style>
/* 样式部分保持不变 */
.chat-container {
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  height: 90%;
  width: 95%;
  border: 1px solid #ccc;
  border-radius: 5px;
  overflow: hidden;
  margin-top: 40px;
  margin-left: 20px;
}

.title-container {
  height: 50px;
  width: 100%;
  background-color: #27ba9b;
  border-radius: 5px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 20px;
  color: white;
}

.message-container {
  flex-grow: 1;
  display: flex;
  justify-content: flex-end;
  padding: 0 10px;
  overflow-y: auto;
}

.message-box {
  display: flex;
  flex-direction: column;
  max-height: 300px;
  width: 100%;
  padding: 10px;
  -ms-overflow-style: none;
}

.message {
  display: inline-block;
  max-width: 70%;
  margin: 5px;
  padding: 10px;
  border-radius: 10px;
  font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
}

.user {
  align-self: flex-end;
}

.ai {
  align-self: flex-start;
}

.avatar {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 5px;
  border-radius: 50%;
  overflow: hidden;
  background-color: cadetblue;
}

.avatar-container {
  position: relative;
  display: inline-block;
  margin-right: 10px;
}

.name-label {
  position: absolute;
  top: 60%;
  transform: translateY(-50%);
  left: calc(100% + 5px);
  font-size: 18px;
  color: #413838;
  white-space: nowrap;
}

.avatar-image {
  width: 100%;
  height: auto;
}

.right {
  align-self: flex-end;
}

.left {
  align-self: flex-start;
}

.user-message {
  background-color: #d5e4df;
  border-radius: 10px;
  padding: 10px;
  align-self: flex-end;
}

.ai-message {
  background-color: #e5e5ea;
  border-radius: 10px;
  padding: 10px;
  align-self: flex-start;
}

.user .avatar.right {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.user .avatar .name-label {
  position: absolute;
  top: 60%;
  transform: translateY(-50%);
  right: calc(100% + 5px);
  font-size: 18px;
  color: #413838;
  white-space: nowrap;
  left: auto;
}

/* Adjustments for the user's avatar */
.user .avatar.right .avatar-image {
  order: 2;
}

.user .avatar.right .name-label {
  order: 1;
}

.input-box {
  display: flex;
  align-items: center;
  padding: 10px;
  border-top: 1px solid #ccc;
}

.input-box select {
  margin-right: 10px;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.input-box textarea {
  flex: 1;
  padding: 8px;
  height: auto;
  overflow-y: scroll;
  font-size: 15px;
  margin-right: 10px;
  border-radius: 5px;
  border: 1px solid #ccc;
}

.input-box button {
  margin-top: 18px;
  padding: 8px 20px;
  border: none;
  border-radius: 5px;
  background-color: #27ba9b;
  color: white;
  cursor: pointer;
}
/* 隐藏滚动条 */
* {
  scrollbar-width: none;
  -ms-overflow-style: none;
}
.message-container::-webkit-scrollbar {
  display: none;
}
.input-box textarea::-webkit-scrollbar {
  display: none;
}

.loading-animation {
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-dot {
  animation: dot-blink 1s infinite;
  margin: 0 3px;
}

@keyframes dot-blink {
  0% {
    opacity: 0;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}
</style>